package com.urfresh.sp.traffic.configure;

import com.urfresh.sp.traffic.service.TrafficListener;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.pool.PooledConnectionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.jms.listener.adapter.MessageListenerAdapter;

/**
 * Created by urfresh.mark on 2016/12/15.
 */
@Configuration
public class MQConfigure {

    @Value("${activemq.url}")
    String url;

    @Bean(destroyMethod = "stop")
    public PooledConnectionFactory pooledConnectionFactory() {
        PooledConnectionFactory factory = new PooledConnectionFactory();
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
        connectionFactory.setBrokerURL(url);
        factory.setConnectionFactory(connectionFactory);
        return factory;
    }

    @Bean
    public JmsTemplate jmsTemplate(PooledConnectionFactory connectionFactory) {
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory(connectionFactory);
        return jmsTemplate;
    }


    @Bean(destroyMethod = "stop", name = "c1")
    public DefaultMessageListenerContainer pointAddContainer(PooledConnectionFactory connectionFactory,
                                                             @Qualifier("trafficListenerAdapter") MessageListenerAdapter adapter) {
        ActiveMQQueue topic = new ActiveMQQueue("traffic_bind_user");
        DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer();
        listenerContainer.setConnectionFactory(connectionFactory);
        listenerContainer.setDestination(topic);
        listenerContainer.setConcurrentConsumers(3);
//        listenerContainer.setMessageListener(mqListener);
        listenerContainer.setMessageListener(adapter);
//        listenerContainer.setSessionTransacted(true);
        return listenerContainer;
    }

    @Bean(name = "trafficListenerAdapter")
    public MessageListenerAdapter trafficListenerAdapter(@Qualifier("trafficListener") TrafficListener listener) {
        MessageListenerAdapter adapter = new MessageListenerAdapter();
        adapter.setDelegate(listener);
        adapter.setDefaultListenerMethod("receiveMessage");
        return adapter;
    }

}
